package com.atguigu.ting.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.app.BaseApp;
import com.atguigu.ting.realtime.bean.AlbumCommentBean;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.funtion.DimAsyncFunction;
import com.atguigu.ting.realtime.util.AtguiguUtil;
import com.atguigu.ting.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/4/14 12:49
 */
public class DwsAlbumCommentWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsAlbumCommentWindow().init(
            40008,
            2,
            "DwsAlbumCommentWindow",
            Constant.TOPIC_DWD_INTERACTION_ALBUM_COMMENT
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 解析成 pojo
        SingleOutputStreamOperator<AlbumCommentBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<AlbumCommentBean> beanStreamWithoutDims = windowAndAgg(beanStream);
        // 3. 补充维度
        SingleOutputStreamOperator<AlbumCommentBean> beanStreamWithDims = joinDim(beanStreamWithoutDims);
        // 4. 写出到 clickhouse
        writeToClickhouse(beanStreamWithDims);
        
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<AlbumCommentBean> beanStreamWithDims) {
        beanStreamWithDims.addSink(FlinkSinkUtil.getClickHouseSink("dws_album_comment_window", AlbumCommentBean.class));
    }
    
    private SingleOutputStreamOperator<AlbumCommentBean> joinDim(
        SingleOutputStreamOperator<AlbumCommentBean> beanStreamWithoutDims) {
        SingleOutputStreamOperator<AlbumCommentBean> albumStream = AsyncDataStream.unorderedWait(
            beanStreamWithoutDims,
            new DimAsyncFunction<AlbumCommentBean>() {
                @Override
                public void addDim(AlbumCommentBean bean,
                                   JSONObject dim) {
                    bean.setAlbumName(dim.getString("ALBUM_TITLE"));
                    bean.setCategory1Id(dim.getString("CATEGORY1_ID"));
                    bean.setCategory2Id(dim.getString("CATEGORY2_ID"));
                    if (dim.getString("CATEGORY3_ID") == null) {
                        System.out.println(dim);
                    } else {
                        System.out.println("dim: " + dim);
                    }
                    bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                }
                
                @Override
                public String getId(AlbumCommentBean bean) {
                    return bean.getAlbumId();
                }
                
                @Override
                public String getTable() {
                    return "dim_album_info";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        SingleOutputStreamOperator<AlbumCommentBean> c3Stream = AsyncDataStream.unorderedWait(
            albumStream,
            new DimAsyncFunction<AlbumCommentBean>() {
                @Override
                public void addDim(AlbumCommentBean bean,
                                   JSONObject dim) {
                    bean.setCategory3Name(dim.getString("NAME"));
                }
                
                @Override
                public String getId(AlbumCommentBean bean) {
                    return bean.getCategory3Id();
                }
                
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        SingleOutputStreamOperator<AlbumCommentBean> c2Stream = AsyncDataStream.unorderedWait(
            c3Stream,
            new DimAsyncFunction<AlbumCommentBean>() {
                @Override
                public void addDim(AlbumCommentBean bean,
                                   JSONObject dim) {
                    bean.setCategory2Name(dim.getString("NAME"));
                }
                
                @Override
                public String getId(AlbumCommentBean bean) {
                    return bean.getCategory2Id();
                }
                
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        return AsyncDataStream.unorderedWait(
            c2Stream,
            new DimAsyncFunction<AlbumCommentBean>() {
                @Override
                public void addDim(AlbumCommentBean bean,
                                   JSONObject dim) {
                    bean.setCategory1Name(dim.getString("NAME"));
                }
                
                @Override
                public String getId(AlbumCommentBean bean) {
                    return bean.getCategory1Id();
                }
                
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<AlbumCommentBean> windowAndAgg(
        SingleOutputStreamOperator<AlbumCommentBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<AlbumCommentBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(AlbumCommentBean::getAlbumId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<AlbumCommentBean>() {
                    @Override
                    public AlbumCommentBean reduce(AlbumCommentBean value1,
                                                     AlbumCommentBean value2) throws Exception {
                        value1.setCommentUserCt(value1.getCommentUserCt() + value2.getCommentUserCt());
                        return value1;
                    }
                },
                new ProcessWindowFunction<AlbumCommentBean, AlbumCommentBean, String, TimeWindow>() {
                    @Override
                    public void process(String albumId,
                                        Context ctx,
                                        Iterable<AlbumCommentBean> elements,
                                        Collector<AlbumCommentBean> out) throws Exception {
                        AlbumCommentBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<AlbumCommentBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(JSONObject::parseObject)
            // 如果一个用户对一个专辑一天时间内多次订阅和取消订阅,则人数只贡献 1
            .keyBy(obj -> obj.getString("user_id") + "_" + obj.getString("album_id"))
            .process(new KeyedProcessFunction<String, JSONObject, AlbumCommentBean>() {
                
                private ValueState<String> lastCommentDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastCommentDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPlayDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<AlbumCommentBean> out) throws Exception {
                    Long ts = obj.getLong("comment_time");
                    String today = AtguiguUtil.tsToDate(ts);
                    String lastPlayDate = lastCommentDateState.value();
                    
                    long commentUserCt = 0;  //评论人数
                    if (!today.equals(lastPlayDate)) {
                        commentUserCt = 1;
                        lastCommentDateState.update(today);
                    }
                    
                    out.collect(AlbumCommentBean.builder()
                                    .albumId(obj.getString("album_id"))
                                    .commentUserCt(commentUserCt)
                                    .ts(ts)
                                    .build());
                    
                    
                }
            });
    }
}
